package com.qyhl.shop.shop.shop;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.shop.R;
import com.qyhl.shop.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.Md5Builder;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.CommonDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.shop.ShopCouponBean;
import com.qyhl.webtv.commonlib.entity.shop.ShopDetailBean;
import com.qyhl.webtv.commonlib.entity.shop.ShopDetailNewsBean;
import com.qyhl.webtv.commonlib.entity.shop.ShopShowcaseBean;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.ResizableImageView;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.ninephotolayout.ShopNinePhotoLayout;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.expandableView.text.ExpandableTextView;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;
import com.qyhl.webtv.module_user.util.LoginUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SHOP_SHOP_DETAIL)
public class ShopDetailActivity extends BaseActivity implements ShopDetailContract.ShopDetailView {
    @BindView(R2.id.follow_btn)
    ImageButton followBtn;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.cover_recycler)
    RecyclerView coverRecycler;
    @BindView(R2.id.follow_num)
    TextView followNum;
    @BindView(R2.id.address_btn)
    TextView addressBtn;
    @BindView(R2.id.description)
    ExpandableTextView description;
    @BindView(R2.id.coupon_recycler)
    RecyclerView couponRecycler;
    @BindView(R2.id.news_title)
    TextView newsTitle;
    @BindView(R2.id.coupon_title)
    TextView couponTitle;
    @BindView(R2.id.news_recycler)
    RecyclerView newsRecycler;
    @BindView(R2.id.news_layout)
    RelativeLayout newsLayout;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.showcase_layout)
    RelativeLayout showcaseLayout;
    @BindView(R2.id.showcase_recycler)
    RecyclerView showcaseRecycler;
    @BindView(R2.id.rush_purchase_btn)
    ResizableImageView rushPurchaseBtn;

    @Autowired(name = "shopId")
    int shopId;

    private ShopDetailPresenter mPresenter;

    private ShopDetailBean mBean;

    private CommonAdapter<String> coverAdapter;

    private List<String> coverList = new ArrayList<>();

    private CommonAdapter<ShopDetailNewsBean> newsAdapter;

    private List<ShopDetailNewsBean> newsList = new ArrayList<>();

    private CommonAdapter<ShopCouponBean> couponAdapter;

    private List<ShopCouponBean> couponList = new ArrayList<>();

    private CommonAdapter<ShopShowcaseBean> showcaseAdapter;

    private List<ShopShowcaseBean> showcaseList = new ArrayList<>();

    @Override
    protected int getContentView() {
        return R.layout.shop_activity_shop_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);

        //统计
        ActionLogUtils.getInstance().onEvent(ActionConstant.SHOP_BROWSE, shopId);

        mPresenter = new ShopDetailPresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(false);

        followBtn.setEnabled(false);

        coverRecycler.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        coverRecycler.setAdapter(coverAdapter = new CommonAdapter<String>(this, R.layout.shop_item_shop_detail_cover, coverList) {
            @Override
            protected void convert(ViewHolder holder, String url, int position) {
                RoundedImageView cover = holder.getView(R.id.cover);

                Glide.with(ShopDetailActivity.this)
                        .load(url)
                        .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                        .into(cover);
            }
        });

        newsRecycler.setLayoutManager(new LinearLayoutManager(this));
        newsRecycler.setAdapter(newsAdapter = new CommonAdapter<ShopDetailNewsBean>(this, R.layout.shop_item_shop_detail_news, newsList) {
            @Override
            protected void convert(ViewHolder holder, ShopDetailNewsBean bean, int position) {
                holder.setVisible(R.id.shop_name, false);

                holder.setText(R.id.date, bean.getCreateTime());

                ExpandableTextView title = holder.getView(R.id.title);
                title.setText(bean.getDetail(), position);

                ShopNinePhotoLayout ninePhotoLayout = holder.getView(R.id.photo_layout);

                ArrayList<String> select = new ArrayList<>(bean.getPicList());
                ninePhotoLayout.setData(select);

                ninePhotoLayout.setDelegate(new ShopNinePhotoLayout.Delegate() {
                    @Override
                    public void onClickNinePhotoItem(ShopNinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
                        MNImageBrowser.showImageBrowser(ShopDetailActivity.this, view, position, (ArrayList<String>) models);
                    }
                });

            }
        });

        couponRecycler.setLayoutManager(new GridLayoutManager(this, 2));
        couponRecycler.setAdapter(couponAdapter = new CommonAdapter<ShopCouponBean>(this, R.layout.shop_item_shop_detail_coupon, couponList) {
            @Override
            protected void convert(ViewHolder holder, ShopCouponBean bean, int position) {
                if (bean.getType() == 1) {
                    holder.setVisible(R.id.tag, false);
                    holder.setVisible(R.id.tag2, true);
                    holder.setText(R.id.coupon_value, (bean.getDiscount() == 0 ? 10 : bean.getDiscount()) + "");
                } else {
                    holder.setVisible(R.id.tag2, false);
                    holder.setVisible(R.id.tag, true);
                    holder.setText(R.id.coupon_value, bean.getReduction() + "");
                }


                if (bean.getThreshold() == 0) {
                    holder.setText(R.id.coupon_limit, "无门槛");
                } else {
                    holder.setText(R.id.coupon_limit, "满" + bean.getThreshold() + "可用");
                }

                holder.setOnClickListener(R.id.get_btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LoginUtils.checkLogin(new LoginUtils.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    String userName = CommonUtils.getInstance().getUserName();
                                    String sign = Md5Builder.encode(bean.getId() + "-" + userName + "-" + CommonUtils.getInstance().getSite());
                                    showLoading();
                                    mPresenter.getCoupon(userName, bean.getId(), sign);
                                } else {
                                    RouterManager.routerLogin(ShopDetailActivity.this, 0);
                                    showToast("尚未登录或登录已失效！");
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });
                    }
                });
            }
        });

        showcaseRecycler.setLayoutManager(new GridLayoutManager(this, 3));

        showcaseRecycler.setAdapter(showcaseAdapter = new CommonAdapter<ShopShowcaseBean>(this, R.layout.shop_item_shop_detail_showcase, showcaseList) {
            @Override
            protected void convert(ViewHolder holder, ShopShowcaseBean bean, int position) {
                holder.setText(R.id.title, bean.getItemName());

                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(ShopDetailActivity.this)
                        .load(bean.getItemPic())
                        .apply(new RequestOptions().error(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                        .into(cover);

                if (TextUtils.isEmpty(bean.getTag())) {
                    holder.setVisible(R.id.tag, false);
                } else {
                    holder.setVisible(R.id.tag, true);
                    holder.setText(R.id.tag, bean.getTag());
                }

                if (bean.getNormType() == 1) {
                    holder.setVisible(R.id.price, false);
                } else {
                    holder.setVisible(R.id.price, true);
                    SpanUtils spUtils = new SpanUtils(ShopDetailActivity.this);
                    spUtils.append("¥").setSpans(new TextAppearanceSpan(ShopDetailActivity.this, R.style.shop_showcase_price_one))
                            .append(StringUtils.splitDouble(bean.getPrice(), true))
                            .setSpans(new TextAppearanceSpan(ShopDetailActivity.this, R.style.shop_showcase_price_two))
                            .append(StringUtils.splitDouble(bean.getPrice(), false))
                            .setSpans(new TextAppearanceSpan(ShopDetailActivity.this, R.style.shop_showcase_price_one));
                    if (bean.getNormType() == 3) {
                        spUtils.appendSpace(2)
                                .append("起").setSpans().setSpans(new TextAppearanceSpan(ShopDetailActivity.this, R.style.shop_showcase_price_one));
                    }
                    TextView price = holder.getView(R.id.price);
                    price.setText(spUtils.create());
                }

            }
        });

        mPresenter.getDetail(shopId, CommonUtils.getInstance().getUserName());
    }

    private void setImageView(RoundedImageView view, String url) {
        Glide.with(ShopDetailActivity.this)
                .load(url)
                .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                .into(view);
    }

    @Override
    protected void setListener() {
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getDetail(shopId, CommonUtils.getInstance().getUserName());
            }
        });

        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(shopId, CommonUtils.getInstance().getUserName());
            }
        });

        coverAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int position) {
                ArrayList<String> mList = new ArrayList<>(coverList);
                MNImageBrowser.showImageBrowser(ShopDetailActivity.this, view, position, mList);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        showcaseAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SHOP_SHOWCASE_DETAIL)
                        .withInt("itemId", showcaseList.get(i).getId())
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });
    }


    @OnClick({R2.id.back_btn, R2.id.follow_btn, R2.id.share_btn, R2.id.contact_btn, R2.id.address_btn, R2.id.rush_purchase_btn, R2.id.showcase_more})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.back_btn) {
            finish();
        } else if (viewId == R.id.follow_btn) {
            LoginUtils.checkLogin(new LoginUtils.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        String userName = CommonUtils.getInstance().getUserName();
                        String sign = Md5Builder.encode(shopId + "-" + userName + "-" + CommonUtils.getInstance().getSite());
                        showLoading();
                        followBtn.setEnabled(false);
                        if (mBean.isFollow()) {
                            mPresenter.unFollowShop(userName, shopId, sign);
                        } else {
                            mPresenter.followShop(userName, shopId, sign);
                        }
                    } else {
                        RouterManager.routerLogin(ShopDetailActivity.this, 0);
                        showToast("尚未登录或登录已失效！");
                    }
                }

                @Override
                public void error(String s) {

                }
            });
        } else if (viewId == R.id.share_btn) {
            ActionLogUtils.getInstance().onEvent(ActionConstant.SHOP_SHARE, shopId);
            String coverUrl;
            if (mBean.getPicList() != null && mBean.getPicList().size() > 0) {
                coverUrl = mBean.getPicList().get(0);
            } else {
                coverUrl = "";
            }

            MShareBoard shareBoard = new MShareBoard(ShopDetailActivity.this, mBean.getId() + "", mBean.getName(), coverUrl, mBean.getDesc(), 37, false);
            shareBoard.showPopupWindow();
        } else if (viewId == R.id.contact_btn) {
            MPermissionUtils.requestPermissionsResult(ShopDetailActivity.this, 11, new String[]{Manifest.permission.CALL_PHONE}, new MPermissionUtils.OnPermissionListener() {
                @Override
                public void onPermissionGranted() {
                    new CommonDialog.Builder(ShopDetailActivity.this)
                            .setTitle("提示", R.color.global_black_lv1)
                            .setMessage("是否要拨打商铺电话？", R.color.global_black_lv2)
                            .setPositiveButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mBean.getPhone()));
                                    startActivity(intent);
                                }
                            }, R.color.global_base)
                            .setNegativeButton("取消", null, R.color.global_gray_lv2).show();
                }

                @Override
                public void onPermissionDenied() {
                    MPermissionUtils.showTipsDialog(ShopDetailActivity.this);
                }
            });


        } else if (viewId == R.id.address_btn) {
            try {
                new CommonDialog.Builder(ShopDetailActivity.this)
                        .setTitle("提示", R.color.global_black_lv1)
                        .setMessage("是否要跳转至高德地图，进行导航？", R.color.global_black_lv2)
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                goNaviByGaoDeMap(mBean.getLatitude(), mBean.getLongitude());
                            }
                        }, R.color.global_base)
                        .setNegativeButton("取消", null, R.color.global_gray_lv2).show();

            } catch (ActivityNotFoundException e) {
                showToast("请安装高德地图！");
            }
        } else if (viewId == R.id.rush_purchase_btn) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.SHOP_RUSH_PURCHASE_LIST)
                    .withInt("shopId", shopId)
                    .navigation();
        } else if (viewId == R.id.showcase_more) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.SHOP_SHOWCASE_LIST)
                    .withInt("shopId", shopId)
                    .navigation();
        }
    }

    /* func:调起高德导航
     * @param lat 纬度
     * @param lon 经度
     * @param dev 是否偏移(0:lat 和 lon 是已经加密后的,不需要国测加密; 1:需要国测加密)
     * @param t  t = 0（驾车）= 1（公交）= 2（步行）= 3（骑行）= 4（火车）= 5（长途客车）
     */
    private void goNaviByGaoDeMap(Double lat, Double lon) throws ActivityNotFoundException {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        //将功能Scheme以URI的方式传入data
        Uri uri = Uri.parse("amapuri://route/plan/" +
                "?sourceApplication=" + ShopDetailActivity.this.getString(R.string.app_name)
                + "&dlat=" + lat
                + "&dlon=" + lon
                + "&dev=0"
                + "&t=0");
        intent.setData(uri);
        intent.setPackage("com.autonavi.minimap");
        ShopDetailActivity.this.startActivity(intent);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(ShopDetailBean bean) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");

        mBean = bean;

        followBtn.setEnabled(true);

        title.setText(bean.getName());

        if (bean.getPicList() != null && bean.getPicList().size() > 0) {
            coverRecycler.setVisibility(View.VISIBLE);
            coverList.clear();
            coverList.addAll(bean.getPicList());
            coverAdapter.notifyDataSetChanged();
        } else {
            coverRecycler.setVisibility(View.GONE);
        }


        followNum.setText(bean.getViewCount() + "");

        addressBtn.setText(bean.getAddress());

        description.setText(bean.getDesc());

        if (bean.getShopCouponDtoList() == null || bean.getShopCouponDtoList().size() < 1) {
            couponTitle.setVisibility(View.GONE);
            couponRecycler.setVisibility(View.GONE);
        } else {
            couponTitle.setVisibility(View.VISIBLE);
            couponRecycler.setVisibility(View.VISIBLE);

            couponList.clear();
            couponList.addAll(bean.getShopCouponDtoList());
            couponAdapter.notifyDataSetChanged();
        }


        if (bean.getShopNewsDtoList() == null || bean.getShopNewsDtoList().size() < 1) {
            newsTitle.setVisibility(View.GONE);
            newsLayout.setVisibility(View.GONE);
        } else {
            newsTitle.setVisibility(View.VISIBLE);
            newsLayout.setVisibility(View.VISIBLE);

            newsList.clear();
            newsList.addAll(bean.getShopNewsDtoList());
            newsAdapter.notifyDataSetChanged();
        }

        if (bean.getItemList() == null || bean.getItemList().size() < 1) {
            showcaseLayout.setVisibility(View.GONE);
        } else {
            showcaseLayout.setVisibility(View.VISIBLE);

            showcaseList.clear();
            showcaseList.addAll(bean.getItemList());
            showcaseAdapter.notifyDataSetChanged();
        }

        if (bean.isFollow()) {
            followBtn.setImageResource(R.drawable.shop_shop_follow_on_icon);
        } else {
            followBtn.setImageResource(R.drawable.shop_shop_follow_off_icon);
        }

        if (bean.isGift()) {
            rushPurchaseBtn.setVisibility(View.VISIBLE);
        } else {
            rushPurchaseBtn.setVisibility(View.GONE);
        }
    }

    @Override
    public void setError(String msg) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        loadMask.setReloadButtonText("点击重试~");
    }

    @Override
    public void getCouponResult(String msg) {
        dismissLoading();
        showToast(msg);
    }

    @Override
    public void followResult(String msg, boolean isFollow) {
        dismissLoading();
        showToast(msg);

        followBtn.setEnabled(true);

        if (msg.contains("成功")) {
            setResult(RESULT_OK);

            mBean.setFollow(isFollow);
            if (isFollow) {
                followBtn.setImageResource(R.drawable.shop_shop_follow_on_icon);
            } else {
                followBtn.setImageResource(R.drawable.shop_shop_follow_off_icon);
            }
        }
    }
}
